﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Douban
{
    /// <summary>
    /// Interaction logic for AuthorizationPromptWindow.xaml
    /// </summary>
    public partial class AuthorizationPromptWindow : Window
    {
        private const int PreventOperationCountingDefault = 5;
        private int _counting;
        private bool _hasActivated = false;

        public AuthorizationPromptWindow()
            : this(PreventOperationCountingDefault)
        {
        }

        public AuthorizationPromptWindow(int counting)
        {
            InitializeComponent();
            this.Activated += AuthorizationPromptWindow_Activated;
            _counting = counting;
            IsAuthorized = false;
        }

        public bool IsAuthorized { get; private set; }
        
        private void AuthorizationPromptWindow_Activated(object sender, EventArgs e)
        {
            if (_hasActivated) return;

            _hasActivated = true;

            this.OKButton.Content = string.Format("确认({0})", _counting.ToString());

            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += (s, args) =>
            {
                if (_counting == 0)
                {
                    timer.Stop();
                    this.OKButton.IsEnabled = true;
                    this.OKButton.Content = "确认";
                    return;
                }

                this.OKButton.Content = string.Format("确认({0})", (--_counting).ToString());
            };

            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Start();
        }

        private void OKButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	IsAuthorized = true;
            Close();
        }

        private void CancelButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Close();
        }
    }
}
